package com.eeda123.jfinal.route;

import com.jfinal.kit.StrKit;
import com.jfinal.render.RenderException;
import com.jfinal.render.TemplateRender;
import com.jfinal.template.Engine;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ray.liu@eeda123.com on 2018/7/10.
 */
public class ExtRender extends TemplateRender {

    public ExtRender(String view) {
        super(view);
    }

    @Override
    public void render() {
        response.setContentType(getContentType());

        Map<Object, Object> data = new HashMap<Object, Object>();
        for (Enumeration<String> attrs = request.getAttributeNames(); attrs.hasMoreElements(); ) {
            String attrName = attrs.nextElement();
            data.put(attrName, request.getAttribute(attrName));
        }

        try {
            OutputStream os = response.getOutputStream();
            int index = DynamicRouteBaseController.DEFAULT_ROUTE.length();
            if(view.startsWith(DynamicRouteBaseController.DEFAULT_ROUTE)){
            	view = view.substring(index+1);
            }

            //是否使用外部定义的Engine
            if(StrKit.isBlank(com.eeda123.jfinal.route.DynamicRouteController.engineName)){
                engine.getTemplate(view).render(data, os);
            }else{
                Engine.use(com.eeda123.jfinal.route.DynamicRouteController.engineName).getTemplate(view).render(data, os);
            }
        } catch (RuntimeException e) {    // 捕获 ByteWriter.close() 抛出的 RuntimeException
            Throwable cause = e.getCause();
            if (cause instanceof IOException) {    // ClientAbortException、EofException 直接或间接继承自 IOException
                String name = cause.getClass().getSimpleName();
                if ("ClientAbortException".equals(name) || "EofException".equals(name)) {
                    return;
                }
            }

            throw e;
        } catch (IOException e) {
            throw new RenderException(e);
        }
    }
}
